import { ReactNode, useState } from 'react';
import Uppy from '@uppy/core';
import XHRUpload from '@uppy/xhr-upload';
import cn from '@uppy/locales/lib/zh_CN';
// import Webcam from '@uppy/webcam';
// import ScreenCapture from '@uppy/screen-capture';
// import ImageEditor from '@uppy/image-editor';
// import OneDrive from '@uppy/onedrive';
// import Instagram from '@uppy/instagram';
import { DashboardModal, useUppy } from '@uppy/react';
import '@uppy/core/dist/style.css';
import '@uppy/dashboard/dist/style.css';
import '@uppy/progress-bar/dist/style.css';
import '@uppy/status-bar/dist/style.css';
import { useToasts } from '@geist-ui/react';
import an58 from '@mmstudio/an000058';
import { Result } from '../api/file/upload.api';
import api from '../../atoms/api';
import { Message as M1, Result as R1 } from '../api/sys/base';
import ShadowAll from '../../components/shadowall';

export default function UpLoader(props: {
	api: string;
	title: string;
	children: ReactNode;
}) {
	const endpoint = api.file.upload;
	const getfile = `${api.file.id}/`;
	const [, toast] = useToasts();
	const [open, setopen] = useState(false);
	const uppy = useUppy(() => {
		const uppy = Uppy({
			allowMultipleUploads: false,
			autoProceed: true,
			debug: true,
			restrictions: {
				maxFileSize: 10737418240,	// 10gb 1024=1kb 1024*1024=1mb 1024*1024*1024=1gb
				maxNumberOfFiles: 1,
				minNumberOfFiles: 1,
				// allowedFileTypes: ['image/*']
			},
			locale: cn
		});
		uppy.use(XHRUpload, {
			fieldName: 'file',
			formData: true,
			method: 'PUT',
			endpoint,
			timeout: 600000	// 10分钟 1000 * 60 * 10
		});
		uppy.on('complete', async (result) => {
			// 以下代码可将上传的内容变成下载链接,放在页面上.
			const [success] = result.successful;
			if (success) {
				const ret = success.response.body as Result;
				if (ret.ok) {
					// save to table sys
					const file = getfile + ret.fileid;
					const r = await an58<R1, M1>(props.api, 'put', {
						src: file
					});
					if (r.ok === true) {
						toast({
							text: '上传成功',
							type: 'success'
						});
						setopen(false);
						window.location.reload();
					} else {
						toast({
							text: `上传失败${r.message}`,
							type: 'error'
						});
					}
					uppy.close();
				} else {
					toast({
						text: '上传失败',
						type: 'error'
					});
				}
			}
		});
		uppy.on('error', () => {
			toast({
				text: '上传失败',
				type: 'error'
			});
		});
		return uppy;
	});

	return <>
		<ShadowAll>
			<div className='c' onClick={() => {
				setopen(true);
			}} >
				<div className='label'>{props.title}</div>
				<div className='value'>
					{props.children}
				</div>
			</div>
		</ShadowAll>
		<DashboardModal closeModalOnClickOutside uppy={uppy} open={open}
			onRequestClose={() => {
				setopen(false);
			}} />

		<style jsx>{`
.c{
	display: flex;
	flex-direction: row;
	justify-content: space-evenly;
	align-items: center;
	cursor: pointer;
}
.label{
	font-size: 1.5rem;
}
.value{
	max-width: 20rem;
}
`}</style>
	</>;
}
